import datetime
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import desc, or_
from app.models import Article, AdminLog
from app.core.extensions import db
from . import admin_blueprint
from app.services.decorators import admin_required


@admin_blueprint.route('/articles', methods=['GET', 'OPTIONS', 'POST'])
@jwt_required(optional=True)
def articles_endpoint():
    """文章接口
    
    GET: 获取文章列表
    POST: 添加新文章
    """
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})
    
    # GET请求：获取列表
    if request.method == 'GET':
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        status = request.args.get('status', None, type=int)
        is_top = request.args.get('is_top', None, type=int)

        # 构建查询
        query = Article.query

        # 根据状态筛选
        if status is not None:
            query = query.filter(Article.status == status)

        # 根据是否置顶筛选
        if is_top is not None:
            query = query.filter(Article.is_top == is_top)

        # 关键词搜索
        if search:
            query = query.filter(
                or_(
                    Article.title.like(f'%{search}%'),
                    Article.second_title.like(f'%{search}%')
                )
            )

        # 执行分页查询
        pagination = query.order_by(Article.is_top.desc(), Article.sort_number.desc(), desc(Article.create_time)).paginate(
            page=page, per_page=per_page, error_out=False
        )

        articles = pagination.items

        # 构建响应数据
        result = {
            'code': 0,
            'message': '获取成功',
            'data': {
                'total': pagination.total,
                'pages': pagination.pages,
                'page': page,
                'per_page': per_page,
                'items': [article_to_dict(article) for article in articles],
                'list': [article_to_dict(article) for article in articles]
            }
        }

        return jsonify(result)
    
    # POST请求：添加新文章
    elif request.method == 'POST':
        data = request.json

        # 提取表单数据
        title = data.get('title')
        second_title = data.get('second_title', '')
        url = data.get('url')
        image_url = data.get('image_url', '')
        is_top = data.get('is_top', 0)
        sort_number = data.get('sort_number', 0)
        status = data.get('status', 1)

        # 验证必要参数
        if not title or not url:
            return jsonify({'code': 1, 'message': '标题和链接URL不能为空'}), 400

        # 创建新文章
        now = datetime.datetime.now()
        article = Article(
            title=title,
            second_title=second_title,
            url=url,
            image_url=image_url,
            update_time=now,
            is_top=is_top,
            sort_number=sort_number,
            status=status,
            create_time=now
        )

        db.session.add(article)

        # 添加操作日志
        log = AdminLog(
            admin_id=get_jwt_identity(),
            action='添加文章',
            ip=request.remote_addr,
            details=f'添加文章 {title}'
        )
        db.session.add(log)

        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '添加成功',
            'data': article_to_dict(article)
        })


@admin_blueprint.route('/articles/<int:article_id>', methods=['GET', 'OPTIONS', 'PUT', 'DELETE'])
@jwt_required(optional=True)
@admin_required
def article_operations(article_id):
    """文章操作接口
    
    GET: 获取文章详情
    PUT: 更新文章信息
    DELETE: 删除文章
    """
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})
        
    article = Article.query.get(article_id)
    if not article:
        return jsonify({'code': 1, 'message': '文章不存在'}), 404

    # GET请求：获取详情
    if request.method == 'GET':
        return jsonify({
            'code': 0,
            'message': '获取成功',
            'data': article_to_dict(article)
        })
    
    # PUT请求：更新文章
    elif request.method == 'PUT':
        data = request.json

        # 更新文章信息
        if 'title' in data:
            article.title = data['title']
        if 'second_title' in data:
            article.second_title = data['second_title']
        if 'url' in data:
            article.url = data['url']
        if 'image_url' in data:
            article.image_url = data['image_url']
        if 'is_top' in data:
            article.is_top = data['is_top']
        if 'sort_number' in data:
            article.sort_number = data['sort_number']
        if 'status' in data:
            article.status = data['status']

        # 更新更新时间
        article.update_time = datetime.datetime.now()

        # 添加操作日志
        log = AdminLog(
            admin_id=get_jwt_identity(),
            action='编辑文章',
            ip=request.remote_addr,
            details=f'编辑文章 {article.title} (ID: {article.id})'
        )
        db.session.add(log)

        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '更新成功',
            'data': article_to_dict(article)
        })
    
    # DELETE请求：删除文章
    elif request.method == 'DELETE':
        # 添加操作日志
        log = AdminLog(
            admin_id=get_jwt_identity(),
            action='删除文章',
            ip=request.remote_addr,
            details=f'删除文章 {article.title} (ID: {article.id})'
        )
        db.session.add(log)

        # 删除文章
        db.session.delete(article)
        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '删除成功'
        })


@admin_blueprint.route('/articles/status/<int:article_id>', methods=['POST', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def update_article_status(article_id):
    """更新文章状态"""
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})
        
    article = Article.query.get_or_404(article_id)
    data = request.json

    if 'status' not in data:
        return jsonify({'code': 1, 'message': '状态参数不能为空'}), 400

    status = data['status']
    article.status = status

    # 添加操作日志
    status_text = '启用' if status == 1 else '禁用'
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action=f'{status_text}文章',
        ip=request.remote_addr,
        details=f'{status_text}文章 {article.title} (ID: {article.id})'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '更新成功',
        'data': article_to_dict(article)
    })


@admin_blueprint.route('/articles/toggle-top/<int:article_id>', methods=['POST', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def toggle_article_top(article_id):
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})
        
    article = Article.query.get_or_404(article_id)

    # 切换置顶状态
    article.is_top = 1 if article.is_top == 0 else 0

    # 添加操作日志
    top_text = '置顶' if article.is_top == 1 else '取消置顶'
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action=f'{top_text}文章',
        ip=request.remote_addr,
        details=f'{top_text}文章 {article.title} (ID: {article.id})'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '更新成功',
        'data': article_to_dict(article)
    })


@admin_blueprint.route('/articles/sort', methods=['POST', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def sort_articles():
    """批量更新文章排序"""
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})
        
    data = request.json

    if not isinstance(data, list):
        return jsonify({'code': 1, 'message': '参数格式错误'}), 400

    for item in data:
        article_id = item.get('id')
        sort_number = item.get('sort_number')

        if article_id and sort_number is not None:
            article = Article.query.get(article_id)
            if article:
                article.sort_number = sort_number

    # 添加操作日志
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='更新文章排序',
        ip=request.remote_addr,
        details='批量更新文章排序'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '更新成功'
    })


def article_to_dict(article):
    """将文章对象转换为字典"""
    return {
        'id': article.id,
        'title': article.title,
        'second_title': article.second_title,
        'url': article.url,
        'image_url': article.image_url,
        'update_time': article.update_time.strftime('%Y-%m-%d %H:%M:%S') if article.update_time else None,
        'is_top': article.is_top,
        'sort_number': article.sort_number,
        'status': article.status,
        'create_time': article.create_time.strftime('%Y-%m-%d %H:%M:%S') if article.create_time else None
    }
